/*
 * (C) 2014-2015 Alibaba Group Holding Limited
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 *
 *     __  ___   ______        ___       __          ___
 *    |  |/  /  /  __  \      /   \     |  |        /   \
 *    |  '  /  |  |  |  |    /  ^  \    |  |       /  ^  \
 *    |    <   |  |  |  |   /  /_\  \   |  |      /  /_\  \
 *    |  .  \  |  `--'  |  /  _____  \  |  `----./  _____  \
 *    |__|\__\  \______/  /__/     \__\ |_______/__/     \__\
 *
 *
 *
 */
//
// Created by KOALA TEAM on 12/19/14.
//


#import "UIView+KLViewLoadFromNib.h"


#if __has_feature(objc_arc_weak)                //objc_arc_weak
#define WEAK weak
#define __WEAK __weak
#define STRONG strong

#define AUTORELEASE self
#define RELEASE self
#define RETAIN self
#define CFTYPECAST(exp) (__bridge exp)
#define TYPECAST(exp) (__bridge_transfer exp)
#define CFRELEASE(exp) CFRelease(exp)
#define DEALLOC self

#elif __has_feature(objc_arc)                   //objc_arc
#define WEAK unsafe_unretained
#define __WEAK __unsafe_unretained
#define STRONG strong

#define AUTORELEASE self
#define RELEASE self
#define RETAIN self
#define CFTYPECAST(exp) (__bridge exp)
#define TYPECAST(exp) (__bridge_transfer exp)
#define CFRELEASE(exp) CFRelease(exp)
#define DEALLOC self

#else                                           //none
#define WEAK assign
#define __WEAK
#define STRONG retain

#define AUTORELEASE autorelease
#define RELEASE release
#define RETAIN retain
#define CFTYPECAST(exp) (exp)
#define TYPECAST(exp) (exp)
#define CFRELEASE(exp) CFRelease(exp)
#define DEALLOC dealloc

#endif


@implementation UIView (ViewLoadFromNib)


+ (id) loadNibNamed:(NSString *) nibName {
    

    return [UIView loadNibNamed:nibName fromBundle:[NSBundle mainBundle] retainingObjectWithTag:1];
}

+ (id) loadNibNamed:(NSString *) nibName fromBundle:(NSBundle *) bundle retainingObjectWithTag:(NSUInteger) tag {
    NSArray * nib = [bundle loadNibNamed:nibName owner:nil options:nil];
    if(!nib) return nil;
    UIView * target = nil;
    for(UIView * view in nib) {
        if(view.tag == tag) {
            target = [view RETAIN];
            break;
        }
    }
    if(target && [target respondsToSelector:@selector(viewDidLoad)]) {
        [target performSelector:@selector(viewDidLoad)];
    }
    return [target AUTORELEASE];
}

+ (id) loadNibNamed:(NSString *)nibName withClass:(Class) aClass
{
    
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:nibName owner:nil options:nil];
    UIView * target = nil;
    for(UIView* item in nib)
    {
        if([item isKindOfClass:aClass]){
            target = [item RETAIN];
        }
    }
    if(target && [target respondsToSelector:@selector(viewDidLoad)]) {
        [target performSelector:@selector(viewDidLoad)];
    }
    return [target AUTORELEASE];
}


@end
